package com.grablist.feihu.grablist.ui.fragment;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.grablist.feihu.grablist.R;
import com.grablist.feihu.grablist.base.BaseFragment;
import com.grablist.feihu.grablist.bean.ClueInfo;
import com.grablist.feihu.grablist.bean.SettingInfo;
import com.grablist.feihu.grablist.comm.Constants;
import com.grablist.feihu.grablist.comm.MyApplication;
import com.grablist.feihu.grablist.event.NetErrorEvent;
import com.grablist.feihu.grablist.event.SettingInfoEvent;
import com.grablist.feihu.grablist.ui.adapter.ClueAdapter;
import com.grablist.feihu.grablist.ui.fragment.biz.GrabHallBiz;
import com.grablist.feihu.grablist.ui.fragment.component.DaggerGrabHallComponent;
import com.grablist.feihu.grablist.ui.fragment.contract.GrabHallContract;
import com.grablist.feihu.grablist.ui.fragment.module.GrabHallModule;
import com.grablist.feihu.grablist.ui.fragment.presenter.GrabHallPresent;
import com.grablist.feihu.grablist.util.LogUtils;
import com.grablist.feihu.grablist.util.PermissionUtils;
import com.grablist.feihu.grablist.util.StringUtils;
import com.jakewharton.rxbinding.view.RxView;
import com.superrecycleview.superlibrary.recycleview.ProgressStyle;
import com.superrecycleview.superlibrary.recycleview.SuperRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.functions.Action1;

public class GrabHallFrag extends BaseFragment implements GrabHallContract.View, SuperRecyclerView.LoadingListener {

    @Inject
    GrabHallPresent mPresenter;
    @Inject
    GrabHallBiz mBiz;

    private ClueAdapter mAdapter;
    private SettingInfo settingInfo = new SettingInfo();

    @Bind(R.id.tv_location)
    TextView mTvLoaction;
    @Bind(R.id.tv_owner)
    TextView mTvOwner;
    @Bind(R.id.tv_filter)
    TextView mTvFilter;

    @Bind(R.id.super_recycler_view)
    SuperRecyclerView superRecyclerView;

    //申请权限
    private final String[] PERMISSIONS = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
    };
    // 打开相机定位请求Code，多个权限请求Code
    private final int REQUEST_CODE_PERMISSIONS = 2;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_grab_hall, container, false);
        ButterKnife.bind(this, view);

        EventBus.getDefault().register(this);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            initLocation();
            startLocation();
        } else {
            requestMorePermissions();
        }

        if (MyApplication.settingInfo == null) {
            settingInfo.setBusinessCircle("");
            settingInfo.setTrainingType("");
        } else {
            settingInfo.setBusinessCircle(StringUtils.isEmpty(MyApplication.settingInfo.getBusinessCircle()) ? "" : MyApplication.settingInfo.getBusinessCircle());
            settingInfo.setTrainingType(StringUtils.isEmpty(MyApplication.settingInfo.getTrainingType()) ? "" : MyApplication.settingInfo.getTrainingType());

        }

        DaggerGrabHallComponent.builder().grabHallModule(new GrabHallModule(this)).build().inject(this);
        mPresenter.setBiz(mBiz);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        superRecyclerView.setLayoutManager(layoutManager);
        superRecyclerView.setRefreshEnabled(true);// 可以定制是否开启下拉刷新
        superRecyclerView.setLoadMoreEnabled(true);// 可以定制是否开启加载更多
        superRecyclerView.setLoadingListener(this);// 下拉刷新，上拉加载的监听
        superRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);// 下拉刷新的样式
        superRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallClipRotate);// 上拉加载的样式
        superRecyclerView.setArrowImageView(R.mipmap.iconfont_downgrey);// 设置下拉箭头

        mPresenter.getList(settingInfo);

        RxView.clicks(mTvOwner)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        mPresenter.toOwner();
                    }
                });

        RxView.clicks(mTvFilter)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        mPresenter.toSelect();
                    }
                });

        return view;
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mBiz.onDestory();
        ButterKnife.unbind(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopLocation();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void refreshComplete() {
        superRecyclerView.completeRefresh();
    }

    @Override
    public void loadMoreComplete() {
        superRecyclerView.completeLoadMore();
    }

    @Override
    public void hasLoadMore(boolean b) {
        superRecyclerView.setNoMore(b);
    }

    @Override
    public void updateList(List<ClueInfo> list) {
//        mAdapter.setDatas(list);
//        adapter.notifyDataSetChanged();
        if (mAdapter == null) {
            mAdapter = new ClueAdapter(getActivity(), list);
            superRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onRefresh() {
        mPresenter.refresh();
        mPresenter.getList(settingInfo);
    }

    @Override
    public void onLoadMore() {
        mPresenter.getList(settingInfo);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSetEvent(SettingInfoEvent info) {
        LogUtils.d("---------------------------------------->");
        settingInfo = info.getSettingInfo();
        onRefresh();
    }

    // 自定义申请多个权限
    private void requestMorePermissions() {
        PermissionUtils.checkMorePermissions(getActivity(), PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
            @Override
            public void onHasPermission() {
                initLocation();
                startLocation();
            }

            @Override
            public void onUserHasAlreadyTurnedDown(String... permission) {
//                showExplainDialog(permission, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        PermissionUtils.requestMorePermissions(getActivity(), PERMISSIONS, REQUEST_CODE_PERMISSIONS);
//                    }
//                });
            }

            @Override
            public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                PermissionUtils.requestMorePermissions(getActivity(), PERMISSIONS, REQUEST_CODE_PERMISSIONS);
            }
        });
    }

    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;

    /**
     * 初始化定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void initLocation() {
        //初始化client
        locationClient = new AMapLocationClient(getActivity());
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }


    /**
     * 默认的定位参数
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
//        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mOption;
    }

    /**
     * 开始定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void startLocation() {
        //根据控件的选择，重新设置定位参数
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    /**
     * 停止定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void stopLocation() {
        // 停止定位
        if (locationClient != null) {
            locationClient.stopLocation();
        }
    }

    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation loca) {
            if (null != loca) {
                Constants.location = loca;
                mTvLoaction.setText(Constants.location.getCity());
                LogUtils.d(Constants.location.getCity());
            }
        }
    };
}
